#!/usr/bin/python
# -*- coding: utf-8 -*-

import cjcx
import socket
import re
import os.path
import time
import sys

print "Content-Type: text/html"
print
import commands
output = commands.getoutput("ps aux")
if len(output.split("cron.py"))>2:
    print "Already Running!"
    sys.exit(0)
count = 0
while True:
    f = open("data/time","a")
    f.write(str(count))
    f.write("\n")
    f.write(str(time.time()) + " ")   
    f.close()
    count = 0
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("121.101.217.125",80))
    get_str = """GET /cronlist.php?cron=ts HTTP/1.1
Connetion: keep-alive
HOST: scutter.rwnest.com

"""
    sock.sendall(get_str)
    head = ""
    chunk = ""
    body = ""
    while True:
        t = sock.recv(1024)
        if "\r\n\r\n" in t:
            loc = t.find("\r\n\r\n")
            head += t[:loc]
            chunk = t[loc+4:]
            break
        else:
            head += t

    while True:
        loc = chunk.find("\r\n")
        if loc==-1: chunk+=sock.recv(1024)
        chunk_len = int(chunk[:loc],16)
        if chunk_len==0:
            break
        chunk = chunk[loc+2:]
        while len(chunk)<chunk_len:
            chunk += sock.recv(1024)
        body += chunk[:chunk_len]
        chunk = chunk[chunk_len+2:]
        
    sock.close()
    body = body.strip()
    users = body.split()
    import cPickle
    from sets import Set
    f = open("data/time","a")
    f.write(str(len(users)) + " ")   
    f.close()
    for user in users:
        userid, passwd = user.split(":")
        keys = []
        try:
            marks = cjcx.query(userid, passwd)
            if not marks: continue
            new_keys = []
            if os.path.exists("data/"+userid):
                fr = open("data/"+userid, "r")
                keys = cPickle.load(fr)
                fr.close()  
                new_keys = list(Set(marks.keys()) - Set(keys))
                
            content = ""
            for new_key in new_keys:
                content += "%s:%s=>" % (marks[new_key][0], marks[new_key][1])
            if content:
                content = content[:-2]
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.connect(("121.101.217.125",80))
                get_str = """GET /mailler.php?jwuser=%s&cron=ts&content=%s HTTP/1.1
Connetion: keep-alive
HOST: scutter.rwnest.com

""" % (userid, content)
                sock.sendall(get_str)
                sock.close()
        except:
            continue
        fw = open("data/"+userid, "w")
        cPickle.dump(marks.keys(), fw)
        fw.close()
        count += 1
